package com.fg114.main.service;

import java.io.InputStream;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.fg114.main.recorder.RecorderUploadUtil;
import com.fg114.main.service.dto.JsonPack;
import com.fg114.main.service.http.A57HttpApiV3;
import com.fg114.main.util.CheckUtil;
import com.fg114.main.util.ContextUtil;
import com.fg114.main.util.SessionManager;
import com.rescueworkers.Settings;
import com.rescueworkers.UploadFileUtils;
import com.rescueworkers.Db.TaskDb;
import com.rescueworkers.dto.UploadVoiceOrImageInfo;
import com.rescueworkers.dto.UserInfoDTO;
import com.rescueworkers.task.UploadVoiceOrImageTask;

public class UploadVoiceOrImageService extends Service {

	private static volatile boolean isRunning=false;
	private static Thread worker = new Thread("uploadVoiceOrImageTask worker") {

		@Override
		public void run() {
			while (true) {
				try {
					try {
						UserInfoDTO user = SessionManager.getInstance().getUserInfo(ContextUtil.getContext());
						String token = user.token;
						if(CheckUtil.isEmpty(token)){
							continue;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					Log.i("TAG", isRunning+" isRunning");
					SystemClock.sleep(1000 * 30);
					if(isRunning){
						continue;
					}
					isRunning=true;
					UploadVoiceOrImageTask task = new UploadVoiceOrImageTask( ContextUtil.getContext());
					
					task.execute(new Runnable() {
						public void run() {
							isRunning=false;
						}
					},new Runnable() {
						public void run() {
							isRunning=false;
						}
					});
				} catch (Throwable e) {
					if(e instanceof InterruptedException){
						return;//结束服务
					}
				}
			}

		}
	};

	@Override
	public void onCreate() {
		try {
			super.onCreate();
			Log.d("---KeepAliveService","onCreate");
			worker.start();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onDestroy() {
		try {
			super.onDestroy();
			Log.d("---KeepAliveService","onDestroy");
			Intent localIntent = new Intent();
			localIntent.setClass(this, UploadVoiceOrImageService.class); //销毁时重新启动Service
			if(worker!=null){
				worker.interrupt();
			}
			this.startService(localIntent);
		}
		catch (Exception e) {
			e.printStackTrace();	
		}
	}


	@Override
	public void onStart(Intent intent, int startId) {
		try {
			super.onStart(intent, startId);
			Log.d("---KeepAliveService","onDestroy");
		}
		catch (Exception e) {
			e.printStackTrace();	
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d("---KeepAliveService","onBind");
		return null;
	}
}
